package com.va.feedback.component;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import com.va.feedback.FeedbackItemConstants;

public class RadioFeedback extends AbstractFeedback {

	private RadioGroup radioGroup;
	private RadioButton radioButton;

	/**
	 * Constructor for RadioFeedback
	 * @param context context of the parent
	 */
	public RadioFeedback(Context context) {
		super(context);
		this.context = context;
		
		addQuestionWidget();
		addAnswerComponent();
	}
	
	/**
	 * Sets the properties
	 */
	@SuppressWarnings("unchecked")
	public void setComponentProperty(String type, Object value) {
		if (FeedbackItemConstants.PROPERTY_QUESTION.equals(type)) {
			String question = (String) value;
			questionWidget.setText(question);
		} else if (FeedbackItemConstants.PROPERTY_RADIO_ITEMS.equals(type)) {
			List<String> items = (ArrayList<String>) value;
			RelativeLayout.LayoutParams radioButtonLayout = new RelativeLayout.LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
			for (int i=0; i<items.size(); i++) {
				radioButton = new RadioButton(context);
				radioButton.setText(items.get(i));
				radioGroup.addView(radioButton, i, radioButtonLayout);
			}
		}
	}
	
	/**
	 * Adds the component which captures the user response to the question widget
	 */
	protected void addAnswerComponent() {
		radioGroup = new RadioGroup(context);
		RelativeLayout.LayoutParams radioGroupLayout = new RelativeLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		radioGroup.setId(2);
		radioGroupLayout.addRule(RelativeLayout.BELOW, 1);
		this.addView(radioGroup, radioGroupLayout);
	}

	/**
	 * Returns the response in the form of a JSONObject
	 * The response is : {'qid': qid, 'answer': text of the option selected by user}
	 */
	public JSONObject getFeedback() throws JSONException {
		int id = radioGroup.getCheckedRadioButtonId();
		if (id == RadioGroup.NO_ID)
			return null;
		RadioButton selectedButton = (RadioButton) radioGroup.findViewById(id);
		String answer = selectedButton.getText().toString();
		JSONObject object = new JSONObject();
		object.put("qid", qid);
		object.put("answer", answer);
		return object;
	}

}
